package com.woniu.permissions.controller;


import cn.hutool.core.bean.BeanUtil;
import com.woniu.model.Result;
import com.woniu.permissions.form.UpdateRoleNameForm;
import com.woniu.permissions.model.Role;
import com.woniu.permissions.param.UpdateRoleNameParam;
import com.woniu.permissions.service.RoleService;
import com.woniu.util.RedisUtil;
import com.woniu.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 吴彦祖
 * @since 2024年05月23日
 */
@RestController
@RequestMapping("/role")
@Api(tags = "角色接口")
public class RoleController {
    @Resource
    private RoleService roleService;
    @Resource
    private RedisUtil redisUtil;
    /**
     * 新增角色
     * @param roleName 角色名
     * @return 输出新增成功的角色对象
     */
    @ApiOperation("新增角色")
    @GetMapping("/addRole/{roleName}")
    public Result<Role> addRole(
            @ApiParam(name = "roleName",value = "角色名称")
            @PathVariable("roleName")
            String roleName,@RequestHeader String token) throws Exception {
        String refreshToken = redisUtil.get(token);
        JwtUtil.parseAdminToken(refreshToken);
            Role role =  roleService.insertRole(roleName);
        return Result.newInstance(Role.class).setData(role).setMessage("新增角色成功");
    }

    /**
     * 根据id修改角色名
     * @param form 角色id
     * @return 输出角色对象
     */
    @ApiOperation("修改角色名")
    @PostMapping("/updateRole")
    public Result<Role> updateRole(@RequestBody UpdateRoleNameForm form,@RequestHeader String token) throws Exception {
        String refreshToken = redisUtil.get(token);
        JwtUtil.parseAdminToken(refreshToken);
        Role role = roleService.updateRole(BeanUtil.toBean(form, UpdateRoleNameParam.class));
        return Result.newInstance(Role.class).setData(role).setMessage("修改角色名成功");
    }

    /**
     * 根据id删除角色
     * @param id 角色id
     * @return 删除的角色对象
     */
    @ApiOperation("根据id删除角色")
    @GetMapping("/delRole/{id}")
    public Result<Role> delRole(
            @PathVariable("id")
            @ApiParam(name = "id",value = "角色id")
            String id,@RequestHeader String token
    ) throws Exception {
        String refreshToken = redisUtil.get(token);
        JwtUtil.parseAdminToken(refreshToken);
        Role role = roleService.delRole(id);
        return Result.newInstance(Role.class).setData(role).setMessage("删除角色成功");
    }
}

